/**
 * 
 */
package com.etlmaster.executor.steps.extract;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.crypto.DesCipher;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.BteqUtil;
import com.etlmaster.executor.utils.StepState;

import freemarker.core.FreeMarkerTemplate;

/**
 * @author Lizq
 *
 */

@StepInstruction("teradataImport")
public class TeradataImportStep extends Step {
	private TeradataImportStepMeta meta;
	/**
	 * @param meta
	 */
	public TeradataImportStep(StepMeta meta) {
		super(meta);
		this.meta=(TeradataImportStepMeta)meta;
	}

	/* (non-Javadoc)
	 * @see com.asiainfo.dacp.dp.executor.Step#handle()
	 */
	@Override
	protected int handle() {
		
		int flag = StepState.RUNNING_SUCCESSED;
		
		DataSourceDefine def = DataSourceHolder.getInstance()
				.getDataSourceDefine(meta.getDsName());
		BteqUtil util=new BteqUtil();
		String server=util.getIP(def.getUrl());

		Map<String, String> data = new HashMap<String, String>();
		data.put("server", server);
		data.put("username",def.getUsername());
		data.put("password",DesCipher.decrypt(def.getPassword()));
		
		data.put("importTablename", meta.getImportTablename());
		data.put("separator", meta.getSeparator());
		data.put("datafile", meta.getDatafile());
		data.put("column", meta.getColumn());
		data.put("override", meta.getOverride());
		data.put("columnDefine", getColumnDefine(meta.getColumn()));
		data.put("columnDefineValue", getColumnDefineValue(meta.getColumn()));
		
		String bteqCmd=FreeMarkerTemplate.getFpl("bteqLoad", data);
		
		if(bteqCmd==null){
			meta.log("INFO","获取BTEQ命令为空，运行失败");
			return StepState.RUNNING_FAILED;
		}else{
		Pattern pattern=Pattern.compile("(\r\n|\r|\n|\n\r)");
		//正则表达式的匹配一定要是这样，单个替换\r|\n的时候会错误
		Matcher matcher=pattern.matcher(bteqCmd);
		bteqCmd=matcher.replaceAll("");
		  
		meta.log("INFO",bteqCmd);
		}
		String result=util.doExecute(bteqCmd);
		if(util.FAULT.equals(result)){
			flag=StepState.RUNNING_FAILED;
		}
		
		return flag;
	}
	private String getColumnDefine(String column){
		String result=column.replaceAll(",", " varchar(2000),");
		result=result+" varchar(2000)";
		return result;
	}
	private String getColumnDefineValue(String column){
		String result=column.replaceAll(",", ",:");
		result=":"+result;
		return result;
	}
	/* (non-Javadoc)
	 * @see com.asiainfo.dacp.dp.executor.Step#stop()
	 */
	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

}
